import { Prisma, PrismaClient } from "@prisma/client";
import { Time } from "./Time";

const prisma = new PrismaClient();

/** 检查 */
export class Check {
   /** 校验必填字段 */
   static Required(arr: Array<any>) {
      const stateList = arr.map(item => {
         if (item == "") return false; // 当字段为空字符串时，返回false
         if (item instanceof Array) return item.length > 0; // 如果参数为数组，判断数组是否为空
         if (item == 0) return true;

         return item != null || item != undefined;
      });
      return !stateList.includes(false);
   }

   /** 效验手机号码 */
   static Mobile(mobile: string) {
      return /^(?:(?:\+|00)86)?1\d{10}$/.test(mobile);
   }

   /** 校验短信验证码 */
   static async Smg(phone: string, code: string) {
      try {
         const his = await prisma.sms.findFirst({
            where: {
               phone,
               code,
               send_time: {
                  gte: new Date(Time.Now().getTime() - 600000)
               }
            }
         });

         return Boolean(his);
      } catch (error) {
         console.log("error", error);
         return false;
      }
   }

   /** 检验字符串是否为 json 格式 */
   static StringIsJSON(str?: Prisma.JsonValue) {
      if (typeof str === "string") {
         try {
            var obj = JSON.parse(str);
            // 等于这个条件说明就是JSON字符串 会返回true
            if (typeof obj == "object" && obj) {
               return true;
            } else {
               //不是就返回false
               return false;
            }
         } catch (e) {
            return false;
         }
      }
      return false;
   }

   /** 检查json数据是否为可用数组 */
   static IsArray<T = any>(value: any): value is Array<T> {
      return Object.prototype.toString.call(value) == "[object Array]";
   }

   /** 检查是否为字符串 */
   static IsString(value: any): value is string {
      return Object.prototype.toString.call(value) == "[object String]";
   }
}
